<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/02/28 19:27:34 $)
// $RCSfile: functions_canned.php,v $ : $Revision: 1.10 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Builds a category array for a provided staff
*/
function buildCategoryData(&$cannedcategoryidlist, $canneddata = false)
{
	global $dbCore, $_SWIFT;

	$categorydata = array();
	$catcount = 0;
	if (!$cannedcategoryidlist)
	{
		$cannedcategoryidlist = array();
	}

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."cannedcategories` WHERE (categorytype = '". SWIFTPUBLIC ."') OR (categorytype = '". SWIFTPRIVATE ."' AND staffid = '". $dbCore->escape($_SWIFT["staff"]["staffid"]) ."') ORDER BY cannedcategoryid ASC;");

	while ($dbCore->nextRecord())
	{
		$catcount = count($categorydata[$dbCore->Record["parentcategoryid"]]);
		$categorydata[$dbCore->Record["parentcategoryid"]][$catcount] = $dbCore->Record;
		$canneddata[$dbCore->Record["cannedcategoryid"]] = $dbCore->Record;
		$cannedcategoryidlist[] = $dbCore->Record["cannedcategoryid"];
	}

	return $categorydata;
}

/**
* Builds a treeview like category select data
*/
function buildCategorySelectData($selectedcatid=0)
{
	global $_SWIFT;
	
	$_option = doCategoryOptionLoop(buildCategoryData(($_temp=array())), 0, $selectedcatid, 1, ($index=1), ($_temp = array()));

	$_option[0]["title"] = $_SWIFT["language"]["parentcategory"];
	$_option[0]["value"] = "0";
	$_option[0]["selected"] = iif($selectedcatid==0, true, false);

	return $_option;
}

/**
* Does a loop on categories to generate data
*/
function doCategoryOptionLoop($data, $parentid, $selectedcatid=0, $indent=0, &$index, &$_option)
{
	$childcount = count($data[$parentid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		$childindent = str_repeat("   ", $indent);
		$childprefix = $childindent."|- ";

		// Iterate through all childs and build the option list
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$data[$parentid][$ii];
			$_option[$index]["title"] = $childprefix.$childdata["title"];
			$_option[$index]["value"] = $childdata["cannedcategoryid"];
			$_option[$index]["selected"] = iif($selectedcatid == $childdata["cannedcategoryid"], true, false);
			$index++;

			// Does it have any sub childs?
			if (count($data[$childdata["cannedcategoryid"]]) > 0)
			{
				// Yup, do another loop for this
			//	$index++;
				doCategoryOptionLoop($data, $childdata["cannedcategoryid"], $selectedcatid, ($indent+1), $index, $_option);
			}
		}
	}
	
	return $_option;
}

/**
* Builds a tree view with category data
*/
function buildCategoryTreeData(&$nodeclass, $selectedcatid=0)
{
	return doCategoryTreeLoop(buildCategoryData(($_temp=array())), 0, $nodeclass, $selectedcatid);
}

/**
* Does a loop on categories to generate tree view data
*/
function doCategoryTreeLoop($data, $parentid, &$nodeclass, $selectedcatid=0)
{
	global $_SWIFT;

	$childcount = count($data[$parentid]);
	if (!is_array($_option))
	{
		$_option = array();
	}
	
	if ($childcount != 0)
	{
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$data[$parentid][$ii];
			$index = $ii+$index;
			$subchilds = count($data[$childdata["cannedcategoryid"]]);

			$_newnode = &$nodeclass->addItem(new HTML_TreeNode(array('text' => "&nbsp;". $childdata["title"] ."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[ <a href='index.php?_m=livesupport&_a=insertcannedcategory&parentcategoryid=". $childdata["cannedcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["addsubcat"] ."'>". $_SWIFT["language"]["addsubcat"] ."</a> | <a href='index.php?_m=livesupport&_a=insertcannedresponse&parentcategoryid=". $childdata["cannedcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["addresponse"] ."'>". $_SWIFT["language"]["addresponse"] ."</a> | <a href='index.php?_m=livesupport&_a=editcannedcategory&cannedcategoryid=". $childdata["cannedcategoryid"] ."' id='blue' title='". $_SWIFT["language"]["editcategory"] ."'>". $_SWIFT["language"]["editcategory"] ."</a> | <a onClick='javascript:doConfirm(\"". $_SWIFT["language"]["catdelactionconfirm"] ."\", \"index.php?_m=livesupport&_a=canned&do=delete&cannedcategoryid=". $childdata["cannedcategoryid"] ."\");' href='#' id='blue' title='". $_SWIFT["language"]["delete"] ."'>". $_SWIFT["language"]["delete"] ."</a> ]", 'link' => "", 'icon' => "icon_folderyellow3.gif", 'expandedIcon' => iif(!$subchilds, "icon_folderyellow3.gif", "icon_folderyellow3.gif"), 'expanded' => true)));

			// Does it have any sub childs?
			if ($subchilds > 0)
			{
				// Yup, do another loop for this
				$index++;
				doCategoryTreeLoop($data, $childdata["cannedcategoryid"], $_newnode, $selectedcatid);
			}
		}
	}
	
	return true;
}

/**
* Deletes a category and all sub categories under it
*/
function deleteCategory($cannedcategoryid)
{
	global $dbCore, $_SWIFT;

	$cannedresponselist = $cannedresponsedatalist = array();
	
	$cannedcategorylist = getSubCategoryList($cannedcategoryid, buildCategoryData(($_temp=array())), ($_temp = array()));

	// Build the response list now
	$dbCore->query("SELECT `cannedresponseid` FROM `". TABLE_PREFIX ."cannedresponses` WHERE `cannedcategoryid` IN (". buildIN($cannedcategorylist) .");");
	while ($dbCore->nextRecord())
	{
		$cannedresponselist[] = $dbCore->Record["cannedresponseid"];
	}

	// ok now start nuking them
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."cannedresponsedata` WHERE `cannedresponseid` IN (". buildIN($cannedresponselist) .");");
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."cannedresponses` WHERE `cannedresponseid` IN (". buildIN($cannedresponselist) .");");
	$dbCore->shutdownQuery("DELETE FROM `". TABLE_PREFIX ."cannedcategories` WHERE `cannedcategoryid` IN (". buildIN($cannedcategorylist) .");");

	return true;
}

/**
* Returns the current category id + all sub categories under it
*/
function getSubCategoryList($cannedcategoryid, $data, &$categorylist)
{
	global $dbCore, $_SWIFT;

	if (!$categorylist)
	{
		$categorylist = array();
		if ($cannedcategoryid != 0)
		{
			$categorylist[] = $cannedcategoryid;
		}
	}

	
	$childcount = count($data[$cannedcategoryid]);
	
	if ($childcount != 0)
	{
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$data[$cannedcategoryid][$ii];
			$index = $ii+$index;

			$categorylist[] = $childdata["cannedcategoryid"];

			// Does it have any sub childs?
			if (count($data[$childdata["cannedcategoryid"]]) > 0)
			{
				// Yup, do another loop for this
				$index++;
				getSubCategoryList($childdata["cannedcategoryid"], $data, $categorylist);
			}
		}
	}
	
	return $categorylist;
}

/**
* Delete a Canned Response
*/
function deleteResponses($cannedresponselist)
{
	global $dbCore, $_SWIFT;

	if (!is_array($cannedresponselist))
	{
		return false;
	}

	if (count($cannedresponselist) == 0)
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."cannedresponsedata` WHERE `cannedresponseid` IN (". buildIN($cannedresponselist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."cannedresponses` WHERE `cannedresponseid` IN (". buildIN($cannedresponselist) .");");

	return true;
}

/**
* Add a new canned category
*/
function addCategory($parentcategoryid, $title, $type)
{
	global $dbCore, $_SWIFT;

	$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."cannedcategories` (`parentcategoryid`, `categorytype`, `staffid`, `title`) VALUES ('". $dbCore->escape($parentcategoryid) ."', '". $dbCore->escape($type) ."', '". iif($type == SWIFTPRIVATE, $_SWIFT["staff"]["staffid"], "0") ."', '". $dbCore->escape($title) ."');");

	return true;
}

/**
* Add a new canned response
*/
function addResponse($cannedcategoryid, $entrytype, $title, $contents)
{
	global $dbCore, $_SWIFT;

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."cannedresponses` (`cannedcategoryid`, `staffid`, `title`, `responsetype`, `dateline`) VALUES ('". $dbCore->escape($cannedcategoryid) ."', '". $dbCore->escape($_SWIFT["staff"]["staffid"]) ."', '". $dbCore->escape($title) ."', '". $dbCore->escape($entrytype) ."', '". DATENOW ."');");
	$cannedresponseid = $dbCore->lastInsertId();

	$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."cannedresponsedata` (`cannedresponseid`, `contents`) VALUES ('". $dbCore->escape($cannedresponseid) ."', '". $dbCore->escape($contents) ."');");

	return true;
}

/**
* Update an existing category
*/
function updateCategory($cannedcategoryid, $parentcategoryid, $title, $type)
{
	global $dbCore, $_SWIFT;

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."cannedcategories` SET `parentcategoryid` = '". $dbCore->escape($parentcategoryid) ."', `categorytype` = '". $dbCore->escape($type) ."', `staffid` = '". iif($type == SWIFTPRIVATE, $_SWIFT["staff"]["staffid"], "0") ."', `title` = '". $dbCore->escape($title) ."' WHERE `cannedcategoryid` = '". $dbCore->escape($cannedcategoryid) ."';");

	return true;
}

/**
* Update Canned Response
*/
function updateResponse($cannedresponseid, $cannedcategoryid, $entrytype, $title, $contents)
{
	global $dbCore, $_SWIFT;

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."cannedresponses` SET `cannedcategoryid` = '". $dbCore->escape($cannedcategoryid) ."', `staffid` = '". $dbCore->escape($_SWIFT["staff"]["staffid"]) ."', `title` = '". $dbCore->escape($title) ."', `responsetype` = '". $dbCore->escape($entrytype) ."', `dateline` = '". DATENOW ."' WHERE cannedresponseid = '". $dbCore->escape($cannedresponseid) ."';");

	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."cannedresponsedata` SET `contents` = '". $dbCore->escape($contents) ."' WHERE cannedresponseid = '". $dbCore->escape($cannedresponseid) ."';");

	return true;
}

/**
* Build the Responses for given categories
*/
function buildResponseData($cannedcategorylist)
{
	global $dbCore, $_SWIFT;

	$responsedata = array();
	$respcount = 0;

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."cannedresponses` AS cannedresponses LEFT JOIN `". TABLE_PREFIX ."cannedresponsedata` AS cannedresponsedata ON (cannedresponses.cannedresponseid = cannedresponsedata.cannedresponseid) WHERE cannedresponses.cannedcategoryid IN (". buildIN($cannedcategorylist) .");");
	while ($dbCore->nextRecord())
	{
		$respcount = count($responsedata[$dbCore->Record["cannedcategoryid"]]);
		$responsedata[$dbCore->Record["cannedcategoryid"]][$respcount] = $dbCore->Record;
	}

	return $responsedata;
}

/**
* Builds the winapp canned XML to send to staff for his chat menu etc
*/
function buildWinappCannedXML(&$xml)
{
	global $dbCore;

	$cannedcategoryidlist = $canneddata = array();
	$categorylist = buildCategoryData($cannedcategoryidlist, $canneddata);
	// Build response list now
	$responselist = buildResponseData($cannedcategoryidlist);

	// Super now lets continue
	$xml->addParentTag("category", array("title" => "Parent"));
	doWinappXMLDataLoop($categorylist, $canneddata, $responselist, $xml, 0);
	// loop through responses
	$responselist = buildResponseData(array(0));
	$responsecount = count($responselist[0]);
	for ($kk=0; $kk<$responsecount; $kk++)
	{
		$xml->addTag("entry", $responselist[0][$kk]["contents"], array("type" => $responselist[0][$kk]["responsetype"], "title" => $responselist[0][$kk]["title"], "id" => $responselist[0][$kk]["cannedresponseid"]));
	}

	$xml->endTag("category");


	return true;
}


/**
* Generates sub category xml and all responses under it
*/
function doWinappXMLDataLoop($categorylist, $canneddata, $responselist, &$xmlpointer, $parentid=0)
{
	$childcount = count($categorylist[$parentid]);

	if ($childcount != 0)
	{
		for ($ii=0; $ii<$childcount; $ii++)
		{
			$childdata = &$categorylist[$parentid][$ii];
			$childid = $childdata["cannedcategoryid"];
			$index = $ii+$index;
			// Does it have any sub childs?
			$xmlpointer->addParentTag("category", array("title" => $childdata["title"]));
			if (count($categorylist[$childdata["cannedcategoryid"]]) > 0)
			{
				// Yup, do another loop for this
				$index++;
				doWinappXMLDataLoop($categorylist, $canneddata, $responselist, $xmlpointer, $childdata["cannedcategoryid"]);
			}

			// loop through responses
			$responsecount = count($responselist[$childid]);
			for ($kk=0; $kk<$responsecount; $kk++)
			{
				$xmlpointer->addTag("entry", $responselist[$childid][$kk]["contents"], array("type" => $responselist[$childid][$kk]["responsetype"], "title" => $responselist[$childid][$kk]["title"], "id" => $responselist[$childid][$kk]["cannedresponseid"]));
			}

			$xmlpointer->endTag("category");
		}
	}

	return true;
}

/**
* Render the category edit/insert form
*/
function renderCategoryForm($type)
{
	global $_SWIFT;

	printFormStart();
	printMainTableHeader(iif($type==INSERT,$_SWIFT["language"]["insertcategory"], $_SWIFT["language"]["editcategory"]));

	printTextRow("title", $_SWIFT["language"]["cattitle"], $_SWIFT["language"]["desc_cattitle"], "text", $_POST["title"]);

	$_options = buildCategorySelectData(iif(empty($_REQUEST["parentcategoryid"]), 0, $_REQUEST["parentcategoryid"]));
	printSelectRow("parentcategoryid", $_SWIFT["language"]["parentcategory"], $_SWIFT["language"]["desc_parentcategory"], $_options);

	printPublicPrivateRow("type", $_SWIFT["language"]["cattype"], $_SWIFT["language"]["desc_cattype"], iif(empty($_POST["type"]), true, $_POST["type"]));


	printSubmitRow(iif($type==INSERT, $_SWIFT["language"]["insert"], $_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "livesupport");
	addHiddenField("_a", iif($type==INSERT,"insertcannedcategory", "editcannedcategory"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("cannedcategoryid", $_REQUEST["cannedcategoryid"]);		
	}
	printFormEnd();
}

/**
* Render the response edit/insert form
*/
function renderResponseForm($type)
{
	global $_SWIFT;

	printFormStart();
	printMainTableHeader(iif($type==INSERT,$_SWIFT["language"]["insertresponse"], $_SWIFT["language"]["editresponse"]));

	printTextRow("title", $_SWIFT["language"]["responsetitle"], $_SWIFT["language"]["desc_responsetitle"], "text", $_POST["title"]);

	$_options = buildCategorySelectData(iif(empty($_REQUEST["parentcategoryid"]), 0, $_REQUEST["parentcategoryid"]));
	printSelectRow("parentcategoryid", $_SWIFT["language"]["parentcategoryres"], $_SWIFT["language"]["desc_parentcategoryres"], $_options);

	unset($_options);
	$_options[0]["title"] = $_SWIFT["language"]["text"];
	$_options[0]["value"] = ENTRY_TEXT;
	$_options[0]["selected"] = true;
	$_options[1]["title"] = $_SWIFT["language"]["url"];
	$_options[1]["value"] = ENTRY_URL;
	$_options[2]["title"] = $_SWIFT["language"]["image"];
	$_options[2]["value"] = ENTRY_IMAGE;
	$_options[3]["title"] = $_SWIFT["language"]["code"];
	$_options[3]["value"] = ENTRY_CODE;

	printSelectRow("responsetype", $_SWIFT["language"]["responsetype"], $_SWIFT["language"]["desc_responsetype"], $_options);

	printTextareaRow("contents", $_SWIFT["language"]["rescontents"], $_SWIFT["language"]["desc_rescontents"], $_POST["contents"], "60", "6");

	printSubmitRow(iif($type==INSERT,$_SWIFT["language"]["insert"], $_SWIFT["language"]["update"]));

	printMainTableFooter();

	addHiddenField("_m", "livesupport");
	addHiddenField("_a", iif($type==INSERT,"insertcannedresponse", "editcannedresponse"));
	addHiddenField("step", "1");
	if ($type == EDIT)
	{
		addHiddenField("cannedresponseid", $_REQUEST["cannedresponseid"]);
	}
	printFormEnd();
}
?>